package permutation;

public class permutation {

	stringbasedonindex t=new stringbasedonindex();
	static int counter = 1;
	String orgarray[];

		
	public permutation(String[] orgarray) {
		this.orgarray = orgarray;
	}

	void permute(int[] arr) {

		if (counter==1){
			print(orgarray);
		//	print1(arr);
			}
		
		int i = arr.length - 2;
		int position1 = 0;
		int position2 = 0;

		// finding position1
		while ((i >= 0)) {

			if ((arr[i] < arr[i + 1])) {

				position1 = i;
				break;
			}

			else {

				i--;
			}

		}
		// finding position2
		for (int j = arr.length - 1; j > 0;) {

			if (arr[j] > arr[position1]) {

				position2 = j;
				break;
			} else {

				j--;

			}

		}

		int temp = arr[position1];
		arr[position1] = arr[position2];
		arr[position2] = temp;

		try {
			int input = position1 + 1;
			
			reverseArray(arr, input); //permutation array is generated here
			
			t.method(orgarray, arr);		
			
			//print1(arr);  
			counter++;
			

		} catch (Exception e) {
			// TODO: handle exception
		} finally {

			while (counter < factorial(arr.length)) {

				permute(arr);
			}

		}

	}

	private void print(String[] iarr) {

		for (int i = 0; i < iarr.length; i++) {

			System.out.print(iarr[i]+" ");

		}
		System.out.println();

	}

	private void print1(int[] iarr) {

		for (int i = 0; i < iarr.length; i++) {

			System.out.print(iarr[i]+" ");

		}
		System.out.println();

	}

	
	public int[] reverseArray(int[] iarr, int rev) {

		int[] copyarr = new int[iarr.length - rev];
		try {

			for (int i = rev, j = copyarr.length - 1; i < iarr.length && j >= 0; i++, j--) {

				copyarr[j] = iarr[i];

			}

		} catch (Exception e) {
			System.out.println("here");

		}

		System.arraycopy(copyarr, 0, iarr, rev, copyarr.length);

		return iarr;

	}

	public int factorial(int i) {

		int sum = 1;
		for (int j = 1; j <= i; j++) {

			sum = sum * j;

		}

//		System.out.println(sum);
		return sum;

	}

}
